#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/12/4 23:53
# @Author  : lizhen
# @Site    : 
# @File    : singleton.py
# @Software: PyCharm


class Singleton1:
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            cls._instance = super(Singleton1, cls).__new__(cls, *args, **kwargs)
        return cls._instance


class Singleton2:
    _obj_list = []

    def __new__(cls, *args, **kwargs):
        if len(cls._obj_list) == 0:
            cls._obj_list.append(super(Singleton2, cls).__new__(cls, *args, **kwargs))
        return cls._obj_list[0]


def singleton3(cls, *args, **kwargs):
    _instance = {}

    def wrapper():
        if cls not in _instance:
            _instance[cls] = cls(*args, **kwargs)
        return _instance[cls]

    return wrapper


@singleton3
class Childclass:
    pass


def main():
    st1_1 = Singleton1()
    st1_2 = Singleton1()
    assert st1_1 is st1_2

    st2_1 = Singleton2()
    st2_2 = Singleton2()
    assert st2_1 is st2_2

    st3_1 = Childclass()
    st3_2 = Childclass()
    assert st3_1 is st3_2


if __name__ == '__main__':
    main()
